import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class extract_cigar_info {

	public static void main(String[] args) {
		String input = args[0];
		split(input);
	}
	
	static void split(String input) {
		int index = 0;
			try(BufferedReader br = new BufferedReader(new FileReader(input))){
				String line;
				while((line = br.readLine()) != null) {
					index++;
					String[] strs = line.split("\t");
					String qry_id = strs[0];
					String ref_id = strs[5];
					int qry_start = Integer.parseInt(strs[2]);
					int qry_end = Integer.parseInt(strs[3]);
					int ref_start = Integer.parseInt(strs[7]);
					String strand = strs[4];
					//transform cigar information to array [cigar_mum] & [cigar_cha]
					String cigar = "";
					for(int i = 0 ; i < strs.length ; i++) {
						if(strs[i].startsWith("cg:Z:")) {
							cigar = strs[i].substring(5);
							break;
						}
					}
					String[] cigar_num_ = cigar.split("[A-Z]");
					String[] cigar_cha_ = cigar.split("\\d+");
					int[] cigar_num = new int[cigar_num_.length];
					for(int i = 0 ; i < cigar_num_.length ; i++) {
						cigar_num[i] = Integer.parseInt(cigar_num_[i]);
					}
					String[] cigar_cha = new String[cigar_cha_.length - 1];
					for(int i = 0 ; i < cigar_cha.length ; i++) {
						cigar_cha[i] = cigar_cha_[i + 1];
					}
					//core operation
					if(strand.equals("+")) {
						int rec_q = qry_start;
						int rec_r = ref_start;
						System.out.println(qry_id + "\t" + rec_q + "\t" + ref_id + "\t" + rec_r + "\t" + strand + "\t" + index);
						for(int i = 0 ; i < cigar_num.length ; i++) {
							if(cigar_cha[i].equals("M")) {
								rec_q += cigar_num[i];
								rec_r += cigar_num[i];
								System.out.println(qry_id + "\t" + rec_q + "\t" + ref_id + "\t" + rec_r + "\t" + strand + "\t" + index);
							}
							else if(cigar_cha[i].equals("I")) {
								rec_q += cigar_num[i];
							}
							else if(cigar_cha[i].equals("D")) {
								rec_r += cigar_num[i];
							}
						}
					}else if(strand.equals("-")) {
						int rec_q = qry_end;
						int rec_r = ref_start;
						System.out.println(qry_id + "\t" + rec_q + "\t" + ref_id + "\t" + rec_r + "\t" + strand + "\t" + index);
						for(int i = 0 ; i < cigar_num.length ; i++) {
							if(cigar_cha[i].equals("M")) {
								rec_q -= cigar_num[i];
								rec_r += cigar_num[i];
								System.out.println(qry_id + "\t" + rec_q + "\t" + ref_id + "\t" + rec_r + "\t" + strand + "\t" + index);
							}
							else if(cigar_cha[i].equals("I")) {
								rec_q -= cigar_num[i];
							}
							else if(cigar_cha[i].equals("D")) {
								rec_r += cigar_num[i];
							}
						}
					}
					
				}
			}catch(IOException e) {
				e.printStackTrace();
			}
	}
}
